package com.highcom.model;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.*;

public class POITest {
    //读取excel 方法一
    @Test
    public void test() throws IOException {
        //加载excel文件路径
        XSSFWorkbook excel = new XSSFWorkbook(
                new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\test.xlsx")));
        //获取第几个sheet
        XSSFSheet sheet = excel.getSheetAt(0);
        for(Row row:sheet){
            for(Cell cell:row){
                System.out.println(cell.getStringCellValue());
            }
        }
        excel.close();
    }
    //方法二
    @Test
    public void test1() throws IOException {
        XSSFWorkbook excel = new XSSFWorkbook(
                new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\test.xlsx")));
        XSSFSheet sheet = excel.getSheetAt(0);
        //获取工作表最后一行的行号
        int lastRowNum = sheet.getLastRowNum();
        for(int i = 0;i<=lastRowNum;i++){
            XSSFRow row = sheet.getRow(i);
            short lastCellNum = row.getLastCellNum();
            for(int j=0;j<lastCellNum;j++){
                XSSFCell cell = row.getCell(j);
                System.out.println(cell.getStringCellValue());
            }
        }
    }
    //写入excel文件
    @Test
    public void test2() throws IOException {
        XSSFWorkbook excel = new XSSFWorkbook();
        XSSFSheet sheet = excel.createSheet("腾讯");
        XSSFRow title = sheet.createRow(0);
        //编写列内容
        title.createCell(0).setCellValue("姓名");
        title.createCell(1).setCellValue("年龄");
        title.createCell(2).setCellValue("地址");

        //编写行内容
        XSSFRow dataRow = sheet.createRow(1);
        dataRow.createCell(0).setCellValue("张三");
        dataRow.createCell(1).setCellValue("30");
        dataRow.createCell(2).setCellValue("道里");

        //写入文件
        FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\test1.xlsx"));
        excel.write(fileOutputStream);
        fileOutputStream.flush();
        excel.close();
    }
}
